package com.cloud.cop.validation;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 实现数据的转换，加密，签名等
 * @author mayh
 *
 */
public class CodeSecretGenerator {

	
	//通过SHA-1 进行签名
	public static String getDigestSHA(String sourceCode){
		return getDigest(sourceCode,"SHA-1");
	}
	
	
	//获得签名
	public static String getDigest(String sourceCode,String digestType){
		try {
			MessageDigest digest = MessageDigest.getInstance(digestType);
			digest.update(sourceCode.getBytes());
			byte[] digests = digest.digest();
			return byte2Hex(digests);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
	
	
	//二进制转十六进制
	public static String byte2Hex(byte[] bytes){
		StringBuilder hs = new StringBuilder();
        String stmp = "";
        for (int n = 0; n < bytes.length; n++) {
            stmp = (Integer.toHexString(bytes[n] & 0XFF));
            if (stmp.length() == 1) {
                hs.append("0");
            }
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
	}
}
